package partner

import (
	"fmt"
	"gitee.com/binny_w/go-util"
	"github.com/gin-gonic/gin"
	"net/http"
	"net/url"
	"time"
)

func RateLimit(redis *util.Redis, rate uint, period time.Duration) gin.HandlerFunc {
	return func(c *gin.Context) {
		ul, _ := url.Parse(c.Request.RequestURI)
		key := fmt.Sprintf("%s:%s", c.ClientIP(), ul.Path)
		if ok, _ := redis.RateLimit(key, rate, period); !ok {
			c.AbortWithStatus(http.StatusTooManyRequests)
		}
		c.Next()
	}
}
